package controllers;

import is.ru.honn.rupin.data.BoardDataGateway;
import is.ru.honn.rupin.data.UserDataGateway;
import is.ru.honn.rupin.domain.Board;
import is.ru.honn.rupin.domain.User;
import is.ru.honn.rupin.service.FollowerService;
import is.ru.honn.rupin.service.PinService;
import is.ru.honn.rupin.service.UserService;
import play.data.Form;
import play.mvc.Result;
import views.html.profile;
import views.html.search.list;

import java.util.List;

/**
 * Controles actions for users and followers such as profile.
 * @author Einar Sigurðsson
 * @version 1.0, 11/19/12
 */
public class UserController extends RuPinController{
    /**
     * adds a follower to the database
     * @param username the user to follow
     * @return profile for username
     */
    public static Result follow(String username){
        if(!Session.isValidated())
            return redirect(routes.Session.login());
        followerService.follow(session().get("username"), username);
        return profile(username);
    }

    /**
     * returns the profile of the current user
     * @return profile of current user
     */
    public static Result myProfile(){
        if(Session.isValidated())
            return profile(session().get("username"));
        else return redirect(routes.Session.login());
    }

    /**
     * returns the user´s profile which matches the username
     * @param username The user who owns the profile
     * @return the profile of the user
     */
    public static Result profile(String username){
        if(!Session.isValidated())
            return redirect(routes.Session.login());
        if(username != null){
            User user = userService.getUser(username);
            if(user != null){
                String name = userService.getUser(username).getName();
                List<Board> boards = pinService.getBoards(username);

                if(!session().get("username").equals(username))
                    return ok(profile.render(boards, name, username, false));
                else
                    return ok(profile.render(boards, name, username, true));
            }
        }
        return notFound();
    }

}
